package org.nearby.note.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/*
 * 数据库操作
 */
public class DbUtil {
	private static Connection mysql_conn = null;
	private static Connection sqlite_conn = null;

	public static Connection getmysqlconnect(boolean new_conn) {
		if (mysql_conn == null || new_conn) {
			return mysqlconnect(new_conn);
		}
		return mysql_conn;
	}

	public static Connection mysqlconnect(boolean new_conn) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			
			String mysql_host = props.get("mysql_host");
			String mysql_user = props.get("mysql_user");
			String mysql_pwd = props.get("mysql_pwd");
			String dbname = props.get("dbname");
			
			Connection conn = DriverManager.getConnection(
					"jdbc:mysql://" + mysql_host + ":3306/" + dbname, mysql_user, mysql_pwd);
			
			if(!new_conn) mysql_conn = conn;
			
			return conn;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static Connection getsqliteconnect(boolean new_conn) {
		if (sqlite_conn == null || new_conn) {
			return sqliteconnect(new_conn);
		}
		return sqlite_conn;
	}

	public static Connection sqliteconnect(boolean new_conn) {
		try {
			Class.forName("org.sqlite.JDBC");
			String pros_file = props.get("sqlite_path");
			
			Connection conn = DriverManager.getConnection("jdbc:sqlite:"
					+ pros_file);
			
			if(!new_conn) sqlite_conn = conn;
			return conn;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	public void getClassPath() {
		System.out.println(getClass().getClassLoader().getResource("")
				.getPath());
	}

	// 窗口关闭时，调用关闭连接
	public static  void close() {
		try {
			if (sqlite_conn != null) {

				sqlite_conn.close();
			}
			if (mysql_conn != null) {
				mysql_conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
